package com.lkx.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkx.common.R;
import com.lkx.pojo.User;
import com.lkx.service.UserService;
import com.lkx.utils.EmailUtil;
import com.lkx.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: com.lkx.controller.UserController
 * @author: likaixin
 * @create: 2022年11月25日 19:32
 * @desc:
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        //获取手机号

        String phone = user.getPhone();
        if (Objects.nonNull(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);

            //调用邮箱库提供的发邮箱服务api完成发送验证码
            ; // 这是个假邮箱，写成你自己的邮箱地址就可以
            String title = "验证码";
            String content = "您好，你的验证码为：" + code + "\t验证码有效期为5分钟，请尽快使用。\n请妥善保管，打死都不要告诉任何人哦";

            emailUtil.sendMessage(phone, title, content);
            //SMSUtils.sendMessage();

            //需要将生成的验证码保存到session
//            session.setAttribute(phone, code);
            //讲生产的验证码缓存到Redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5l, TimeUnit.MINUTES);
            return R.success("邮箱验证码发送成功");
        }

        return R.error("短信发送失败");
    }

    /**
     * @Date: 2022-11-26
     * @Time: 10:46
     * @Param: []
     * @return: com.lkx.common.R<java.lang.String>
     * @desc: 移动端用户登录
     **/
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {
        //获取前端传过来的电话和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //Object attribute = session.getAttribute(phone);
        //从redis中获取缓存验证码
        String result = (String) redisTemplate.opsForValue().get(phone);

        if (result==null){
            return R.error("验证码已过期，请重新获取");
        }

        //判断传过来的参数是否为空
        if (Objects.nonNull(phone) && Objects.nonNull(code) && Objects.nonNull(result) && result.equals(code)) {
            LambdaUpdateWrapper<User> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(User::getPhone, phone);//拿邮箱比较
            User user = userService.getOne(lqw);
            if (user == null) {  //如果为空说明是新用户，将新用户保存到数据库中
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            redisTemplate.delete(phone);
            return R.success(user);

        }
        return R.error("验证码错误！请重新输入！");
    }
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
